<template>
	<view class="warp">
		<view class="content">
			<image class="hdimg" :src="img" mode="widthFix"></image>
			<view class="midbox">
				<view class="golfsum">
					<view class="num">{{sum}}</view>
					<view class="text">总杆数</view>
				</view>
				<view class="addTime">
					<view class="time">{{ getTime2(resData.StartTime) + ' ' + getWeek(resData.StartTime) + ' '+getTime3(resData.StartTime)}}</view>
					<view class="addre">{{resData.ShopName}}</view>
				</view>
			</view>
			<view class="downbox">
					<view class="flaghole">
						<view class="numbox" v-for="(item,index) in resData.Items" :key="index">
							<view class="hole">{{item.HoleNO}}</view>
							<view class="difference" :class="item.Hit_Num > item.Score?'bg4':''">{{difference(item.Hit_Num,item.Score)}}</view>
						</view>
						
					</view>
					<image class="code" src="https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/17188771800961437.png"></image>
			</view>
		</view>
		
		<canvas canvas-id="hoCanvas" class="hoCanvas" :style="{ height: lineBgHeight + 'px' }"></canvas>
		<!-- #ifdef MP-WEIXIN -->
		<button v-if="btnshow" @click="saveImageToAlbum">保存到相册</button>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<button v-if="btnshow" @click="saveImageapp">保存相册</button>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
                userratio:'',
                resData:{},
                sum:0,
                goflid:'',
				user: [],
				btnshow: false,
				show: false,
				img: '../../static/img/test.png',
				qr: '',
				postUrl: '',
				canvasW: '',
				canvasH: '',
				_rpx: '',
				ratio: '',
				windowWidth: '',
				windowHeight: '',
				cW: '',
				cH:'',
				
				img_w:'',
				img_h:'',
				userwidth:'',
                userheight:'',
				user_name:'',
				img3:'',
				lineBgHeight:570
			};
		},
		watch: {
			'qr': {
				handler(val) {
					console.log(val);
					// this.saveImg();
				},
				immediate: true,
				deep: true
			}
		},
		async onLoad(e) {
            this.goflid = e.id
			uni.getSystemInfo({
				success: (res) => {
					this.cW = res.windowWidth;
					this.cH=res.windowHeight;
				}
			})
            this.golfDetail()
			this.img3 = "https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1718093981824195.png"
		},
		async onReady() {
			await this.getUserInfo();

			await this.CreateShareQR();

			await this.saveImg();
		},
		computed: {
			getTime2() {
				return (l) => {
					let d = new Date(l);
					let timestamp = d.getTime();
					return this.$util.unixDatetime(timestamp, 'year');
				};
			},
			getTime3() {
				return (l) => {
					let d = new Date(l);
					let timestamp = d.getTime();
					return this.$util.unixDatetime(timestamp, 'hh-mm');
				};
			}
		},
		methods: {
			difference(Hit_Num,Score){
					if((Score - Hit_Num) > 0){
						return '+'+(Score - Hit_Num)
					}else if((Hit_Num - Score) == 0){
						return 0
					}else if((Score - Hit_Num) < 0){
						return '-'+(Hit_Num - Score)
					}
			},
            async golfDetail(){
                let res = await this.$api.post('GolfHole/RoundDetail',{
                    ID:this.goflid
                })
                if(res.code == 0){
                    this.resData = res.data
                }
                for (let i = 0; i < this.resData.Items.length; i++) {
                    this.sum =Number(this.sum) + Number(this.resData.Items[i].Score) 
                    
                }
                console.log(this.sum,'sum');
            },

			async getUserInfo() {
				let u = uni.getStorageSync('user');
				console.log(u.UserID);
				let res = await this.$api.post('User/GetUserInfo', {
					ID: u.UserID
				});

				this.user = res.data;
				
				this.img = this.user.UserImgs;
				this.user_name=this.user.Name;
				
				let that=this;
				uni.getImageInfo({
					src: 'https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1718355071624415.png',
					success: function(res) {
					},
					fail: (res) => {
						
					}
				});
			},

			async CreateShareQR() {
				// let res = await this.$api.post('Action/CreateShareQR', {
				// 	Page: 'pages/tab/home',
				// })
				// console.log('qr');
				// console.log(res);
				// this.qr = res.data;
				this.qr = 'https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/17188771800961437.png';
				
			},

			saveImg() {
				var that = this;
				let promise1 = new Promise(function(resolve, reject) {
					console.log('promise1', that.img);
					uni.getImageInfo({
						src: 'https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1718854439582184.png',
						success: function(res) {
							console.log('promise1--', res);
                            that.userwidth = res.width
                            that.userheight = res.height
                            that.ratio = res.width/res.height
                            console.log(that.userwidth,that.userheight,that.ratio ,'that.ratio');
							resolve(res);
						},
						fail: (res) => {
							reject(res)
							console.log('promise1错误');
							console.log(res);
						}
					});
				});
				let promise2 = new Promise(function(resolve, reject) {
					console.log('------');
					console.log('promise2', that.qr);
					uni.getImageInfo({
						src: that.qr,
						success: function(res) {
							console.log('promise2--', res);
							that.show = true
							resolve(res);
						},
						fail: (res) => {
							reject(res)
							console.log('promise2错误');
							console.log(res);
						}
					})
				});
				
				let promise3 = new Promise(function(resolve, reject) {
					
					uni.getImageInfo({
						src: that.img,
						success: function(res) {
							console.log('promise3--', res);
                            that.img_w=res.width;
						    that.img_h=res.height;
                            that.userratio =  res.width / res.height
							that.show = true
							resolve(res);
						},
						fail: (res) => {
							reject(res)
							console.log('promise3错误');
							console.log(res);
						}
					})
				});
				// wx.getSystemInfo({
				// 	success: (res) => {
				// 		//that._rpx = res.windowWidth / 375;
				// 		that.ratio = res.windowWidth / res.windowHeight
				// 		// this.windowWidth = res.windowWidth
				// 		// this.windowHeight = res.windowHeight
				// 	},
				// })
                setTimeout(()=>{
                    const query = uni.createSelectorQuery();
				    query.select('.hoCanvas').fields({
							node: true, //指定要获取的属性，这里设置为size: true表示要获取尺寸信息。
							size: true, //在回调函数(res) => {...}中处理查询结果。回调函数会接收一个res参数，其中包含了查询的结果信息。
						},
						(res) => {
							// const dpr = wx.getWindowInfo().pixelRatio
							
							// 在回调函数中，通过res.width和res.height获取到查询元素的宽度和高度。
							console.log(res,'resres');
							
							let hdheight = (331/that.userratio)+10
							const imgRatio = Number(that.ratio) 
							console.log(imgRatio);
							let bNum = 1
							that.canvasW = 351 *bNum;
							that.canvasH = 570 * bNum;
							that.lineBgHeight = hdheight+150
							console.log(this.canvasW,this.canvasH);
							// 绘制图片：图片居中显示在 canvas 中

							Promise.all([promise2, promise1,promise3]).then((res) => {
								that.show = true
								uni.showLoading({
									title: '海报图片生成中...',
									icon: 'loading',
									duration: 1000,
								});
								
								/* 图片获取成功才执行后续代码 */
								var canvas = uni.createCanvasContext('hoCanvas');
								canvas.canvasWidth = that.canvasW; // 背景图片的实际宽度
                				canvas.canvasHeight = that.lineBgHeight ;
                                console.log(res[1].path,'res[1].path');
								// 绘制背景图
								canvas.drawImage(res[1].path, 0, 0, that.userwidth,that.userheight);
								

								//绘制头像
								canvas.drawImage(res[2].path, 10,10, 331, 331/that.userratio);
								//顶端矩形蒙版
								//canvas.fillStyle='rgba(0, 0, 0, 0.3)';
								//canvas.fillRect(0,0, this.canvasW,60);
                                canvas.font='bold 28px Arial';
								canvas.setFillStyle('#706EEE');
								canvas.setStrokeStyle('#706EEE');
								canvas.textAlign = 'center'
                                canvas.fillText(that.sum,62/2,hdheight+35);
                                canvas.font='500 12px Arial';
								canvas.setFillStyle('#333333');
								canvas.setStrokeStyle('#333333');
								canvas.textAlign = 'right'
                                canvas.fillText('总杆数',50,hdheight+50);
								canvas.textAlign = 'left'
                                canvas.font='500 12px Arial';
								canvas.setFillStyle('#333333');
								canvas.setStrokeStyle('#333333');
								let timeText = that.getTime2(that.resData.StartTime) + ' ' + that.getWeek(that.resData.StartTime) + ' '+that.getTime3(that.resData.StartTime)
								let timeWidth = canvas.measureText(timeText).width
                                canvas.fillText(timeText,canvas.canvasWidth-timeWidth-13,hdheight+26);
                                canvas.font='500 12px Arial';
								canvas.setFillStyle('#333333');
								canvas.setStrokeStyle('#333333');
								let textWidth = canvas.measureText(that.resData.ShopName).width
								canvas.textAlign = 'left'
								canvas.fillText(that.resData.ShopName, canvas.canvasWidth-textWidth-13,hdheight+46);
								canvas.textAlign = 'left'
								that.drawCircleImage(canvas,that.resData.Items,hdheight)
								// 绘制活动二维码
								canvas.drawImage(res[0].path,253, hdheight+58, 84, 84);
								// canvas.textAlign = 'left'
								canvas.font='500 14px Arial';
								canvas.setFillStyle('#999999');
                                canvas.setStrokeStyle('#999999');
								// canvas.fillText('长按识别二维码',118 * bNum,this.canvasH*0.85);
								canvas.font='bold 14px Arial';
								canvas.setFillStyle('#333333');
                                canvas.setStrokeStyle('#333333');
								// canvas.fillText('加入挥友圈高尔夫比拼~',118 * bNum,this.canvasH*0.89);
								canvas.scale(2,2);
								
								canvas.draw();

								setTimeout(function() {									
									uni.canvasToTempFilePath({
										x: 0,
										y: 0,
										width: that.canvasW,
										height:that.lineBgHeight,
										destWidth: that.canvasW*2,
										destHeight: that.lineBgHeight*2,
										// destWidth: 375 ,
										// destHeight: 660,
										canvasId: 'hoCanvas',
										success: function(res) {
											console.log(res.tempFilePath,'111');
											
											that.postUrl = res.tempFilePath;
											// that.saveImageToAlbum();
											that.btnshow = true
											uni.hideLoading();
										},
										fail: function(res) {
											console.log(res,'err');
											
										},
									},this);

								}, 3000);
							}).catch(err => {
								console.dir('出错了', err);
								console.log(err);
								uni.showModal({
									title: '异常错误',
									content: '图片生成失败!!!\n[QRError:Damaged QR code]',
									showCancel: false,
									success: (res) => {
										if (res.confirm) uni.navigateBack()
									}
								})
							})

						}
					)
					.exec();
                },1000)
				
			},
			drawCircleImage(ctx, list,height) {
				for (let i = 0; i < list.length; i++) {
						if(i > 8){
							ctx.font='500 12px Arial';
							ctx.setFillStyle('#666666');
							ctx.setStrokeStyle('#666666');
							ctx.textAlign = 'center'
							ctx.fillText(list[i].HoleNO, 20+((i-9)*25),height+117);
							if(list[i].Hit_Num > list[i].Score){
								ctx.beginPath();
								ctx.fillStyle = '#706EEE'
								ctx.arc(20+((i-9)*25), height+130, 12, 0, 2 * Math.PI);
								ctx.fill();
							}
							ctx.font='700 12px Arial';
							ctx.setFillStyle('#333333');
							ctx.setStrokeStyle('#333333');
							if(list[i].Hit_Num > list[i].Score){
								ctx.setFillStyle('#fff');
								ctx.setStrokeStyle('#fff');
							}
							ctx.fillText(this.difference(list[i].Hit_Num,list[i].Score), 20+((i-9)*25),height+134);
						}else{
							ctx.textAlign = 'center'
							ctx.font='500 12px Arial';
							ctx.setFillStyle('#666666');
							ctx.setStrokeStyle('#666666');
							ctx.fillText(list[i].HoleNO, 20+((i)*25),height+75);
							if(list[i].Hit_Num > list[i].Score){
								ctx.beginPath();
								ctx.fillStyle = '#706EEE'
								ctx.arc(20+((i)*25), height+91, 12, 0, 2 * Math.PI);
								ctx.fill();
							}
							ctx.font='700 12px Arial';
							ctx.setFillStyle('#333333');
							ctx.setStrokeStyle('#333333');
							if(list[i].Hit_Num > list[i].Score){
								ctx.setFillStyle('#fff');
								ctx.setStrokeStyle('#fff');
							}
							ctx.fillText(this.difference(list[i].Hit_Num,list[i].Score), 20+((i)*25),height+95);
						}
						
				}
			},
			saveImageToAlbum: function() {
				var that = this;
				//将图片保存到相册
				uni.saveImageToPhotosAlbum({
					filePath: that.postUrl,
					success(res) {
						uni.showModal({
							title: '保存成功',
							content: '图片成功保存到相册了，快去分享朋友圈吧',
							showCancel: false,
							confirmText: '好的',
							confirmColor: '#818FFB',
							success: function(res) {
								if (res.confirm) {}
								// that.hideShareImg()
							},
						});
					},
				});
			},
			saveImageapp(){
				uni.getImageInfo({
					src: this.postUrl,
					success: function(res) {
						let path = res.path;
						uni.saveImageToPhotosAlbum({
							filePath: path,
							success(res) {
							uni.showToast({
								title: '保存成功',
								icon: "none"
							})
							},
							ail(res) {
								uni.showToast({
									title: '保存失败',
									icon: "none"
								})
							}
						})
					}
				})
				console.log('1111111');
				console.log(this.postUrl,'2222');
			},
		},
	};
</script>

<style lang="scss">
page{
	background-color: #f6f6f6;
}
	.warp {
		width: 100%;
		box-sizing: border-box;
		padding-bottom: 160rpx;
	}
	.content{
		width: 702rpx;
		// height: 1140rpx;
		background: #FFFFFF;
		padding: 20rpx;
		box-sizing: border-box;
		margin: 24rpx auto;
		.hdimg{
			width: 662rpx;
			height: 802rpx;
			margin-bottom: 26rpx;
		}
		.midbox{
			display: flex;
			align-items: center;
			justify-content: space-between;
			.golfsum{
				.num{
					font-size: 56rpx;
					font-weight: bold;
					color: #706EEE;
				}
				.text{
					font-size: 24rpx;
					color: #333333;
				}
			}
			.addTime{
				.time{
					font-size: 24rpx;
					color: #333333;
					margin-bottom: 16rpx;
				}
				.addre{
					font-size: 24rpx;
					color: #333333;
					text-align: end;
				}
			}
		}
		.downbox{
				display: flex;
				align-items: center;
				.flaghole{
					display: flex;
					flex-wrap: wrap;
					width: 484rpx;
					margin-left: -16rpx;
					.numbox{
						width:calc(100% / 9);
						text-align: center;
					}
					.hole{
						font-size: 24rpx;
						color: #666666;
					}
					.difference{
						font-size: 24rpx;
						color: #333333;
						font-weight: bold;
						width: 36rpx;
						height: 36rpx;
						text-align: center;
						line-height: 36rpx;
						margin: 0 auto;
						border-radius: 50%;
					}
					.bg4{
						background-color: #706EEE;
						color: #fff !important;
					}
				}
				.code{
					width: 160rpx;
					height: 160rpx;
					margin-left: 36rpx;
				}
			}
	}	
	.hoCanvas {
		width: 351px;
		height: 570px;
		margin: 50rpx auto;
		margin-bottom: 0;
		box-sizing: border-box;
		position:fixed;
		left: -200%;
		top: -200%;
		opacity: 0;
		z-index: -99;
	}

	.height70 {
		height: 70vh;
	}
	
	.height100 {
		height: 100vh;
	}

	.height64 {
		height: 62vh;
	}

	button {
		position: fixed;
		left: 50%;
		bottom: 40rpx;
		transform: translate(-50%, -50%);
		background-color: #706EEE;
		color: #fff;
		border-radius: 16rpx;
		width: 90vw;
		margin: 0 auto;
        z-index: 1000;
	}
</style>